/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;



/**
 *
 * @author sheked & nives
 */
public class ProducteDB {
    private QueryRunner run;
    private MapListHandler mlh;
    private MapHandler mh;

    public ProducteDB() throws NamingException, SQLException {
            Context ctx = new InitialContext();
            DataSource odsconn = (DataSource)ctx.lookup("jdbc/volansbd");
            run = new QueryRunner(odsconn);
            mlh = new MapListHandler();
            mh = new MapHandler();
    }

    public List<Map<String,Object>> consultaLlista(int tipus, String id) throws SQLException {
        String columna;
        switch (tipus) {
            case 1: //categoria
                columna = "id_cat";
                break;
            case 2: //subcategoria
                columna = "id_subcat";
                break;
            default:
                columna = "id_subcat";
        }
        return run.query("select id_prod,nom,preu,stock from productes where " + columna + "=?", mlh, id);
    }

    public Blob consultaImatge(int id) throws SQLException {
        return (Blob) run.query("select foto from productes where id_prod=?", mh, id).get("foto");
    }

    public Map<String, Object> consultaProducte(int id) throws SQLException {
        return run.query("select * from productes where id_prod=?", mh, id);
    }
}
